package com.citcc.api.netty.utils;

import java.io.UnsupportedEncodingException;

/**
 * @author liyachong
 * @date 2019/4/4
 * @time 13:54
 */
public class HexUtil {
    public static String toHexString(String s){
        return Long.toHexString(Long.parseLong(s)).toUpperCase();
    }

    /**
     * 16进制字符串转换成byte数组 * byte[] * @param hex
     */
    public static byte[] hexStringToByte(String hex) {
        hex = hex.toUpperCase();
        int len = (hex.length() / 2);
        byte[] result = new byte[len];
        char[] achar = hex.toCharArray();
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
        }
        return result;
    }
    private static byte toByte(char c) {
        byte b = (byte) "0123456789ABCDEF".indexOf(c);
        return b;
    }

    /**
     * 校验和
     *
     * @param msg 需要计算校验和的byte数组
     * @param length 校验和位数
     * @return 计算出的校验和数组
     */
    public static byte[] SumCheck(byte[] msg, int length) {
        long mSum = 0;
        byte[] mByte = new byte[length];

        /** 逐Byte添加位数和 */
        for (byte byteMsg : msg) {
            long mNum = ((long)byteMsg >= 0) ? (long)byteMsg : ((long)byteMsg + 256);
            mSum += mNum;
        } /** end of for (byte byteMsg : msg) */

        /** 位数和转化为Byte数组 */
        for (int liv_Count = 0; liv_Count < length; liv_Count++) {
            mByte[length - liv_Count - 1] = (byte)(mSum >> (liv_Count * 8) & 0xff);
        } /** end of for (int liv_Count = 0; liv_Count < length; liv_Count++) */


        byte[] lmByte = new byte[length];
        int i=mByte.length-1;
        for (byte b : mByte) {
            lmByte[i--]=b;
        }
        return lmByte;
    }
    
    /**
     * 补全位数不够的定长参数 有些定长参数，实际值长度不够，在后面补0x00 * byte[] * @param length * @param pwdByte * @return
     */
    public static byte[] getBytesWithLengthAfter(int length, byte[] pwdByte) {
        byte[] lengthByte = new byte[length];
        for (int i = 0; i < pwdByte.length; i++) {
            lengthByte[i] = pwdByte[i];
        }
        for (int i = 0; i < (length - pwdByte.length); i++) {
            lengthByte[pwdByte.length + i] = 0x00;
        }
        return lengthByte;
    }
    
    //16进制前补0
    public static String befor0(String s,int i){
		
		int l=s.length();
		if(l<i){
			for(int j=0;j<i-l;j++){
				s="0"+s;
			}
		}else{
			s= s.substring(0, 8);
		}
		return s;
	}
    
    public static String hexHighLow(String s){
    	StringBuffer buffer = new StringBuffer(); // 反转后的字符串
		for (int i = s.length() - 2; i >= 0; i = i - 2)
		{
			buffer.append(s.substring(i, i+2));
		}
		System.out.println(buffer.toString());
		return buffer.toString();
    }
    
    public static void main(String[] args) throws UnsupportedEncodingException {
    	float f = 12.23f;
    	String hex = Integer.toHexString(Float.floatToIntBits(f));
    	System.out.println(hex);
	}
}
